package cn.wit.summit.chwan.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.ui.receiver.BroadcastAction;
import pub.devrel.easypermissions.EasyPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lala on 14/12/23.
 */
public class APKUtils {
    private static APKUtils instance;
    Context context;

    private APKUtils(Context context) {
        this.context = context;
    }

    public static APKUtils getInstance(Context context) {
        if (instance == null) {
            instance = new APKUtils(context.getApplicationContext());
        }
        return instance;
    }

    /**
     * 检测是否已安装
     *
     * @param pak 包名
     * @return
     */
    public boolean checkInstall(Context context, String pak) {
        boolean install = false;
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(pak, PackageManager.GET_ACTIVITIES);
            if (info != null && info.activities!=null && info.activities.length > 0) {
                install = true;
            }
        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
        }
        return install;
    }

    /**
     * 安装APK
     *
     * @param
     */

    public void installAPK(Context context, String apkPath, String gameid) {
        if (StringUtils.isEmpty(apkPath))return;
        File apkFile = new File(apkPath);
        StatFactory.getInstance().sendGameInstall(context,gameid,3+"");
        DownLoadTaskTable taskTable = DownloadTaskManager.getInstance().findByGameId(gameid);
        if (taskTable!=null && !StringUtils.isEmpty(taskTable.getPackageName())){
            DownloadTaskManager.getInstance().updateStatusByPackageName(taskTable.getPackageName(), DownLoadStatusConfig.INSTALLING);
        }
        if (!apkFile.exists()) {
            taskTable.setDownStatus(DownLoadStatusConfig.NORMAL);
            DownloadTool.downloadGame(context, taskTable, null);
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            boolean haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
            haveInstallPermission = true;
            if (haveInstallPermission) {
//代码安装
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(context, "cn.wit.summit.chwan.fileprovider", apkFile);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                try {
                    context.startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
        }
        if (EasyPermissions.hasPermissions(context, Manifest.permission.REQUEST_INSTALL_PACKAGES)) {
            //代码安装
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(context, "cn.wit.summit.chwan.fileprovider", apkFile);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            try {
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Intent intentPremiss = new Intent(BroadcastAction.ACTION_INSTALL_APK);
//        intentPremiss.putExtra("apkpath",apkPath);
            context.sendBroadcast(intentPremiss);

        }


    }

    /**
     * 获取已安装APK的信息
     *
     * @param ctx
     * @param pak
     * @return
     */
    public APKInfo getInstallAPKInfo(Context ctx, String pak) {
        APKInfo apkInfo = new APKInfo();
        int versionCode = 0;
        String versionName = null;
        String appName = null;
        String pakName = pak;
        Drawable icon = null;
        PackageManager pm = ctx.getPackageManager();
        PackageInfo appinfo;
        try {
            appinfo = pm.getPackageInfo(pak, PackageManager.GET_ACTIVITIES);
            if (appinfo != null) {
                versionName = appinfo.versionName;
                versionCode = appinfo.versionCode;
                appName = appinfo.applicationInfo.loadLabel(ctx.getPackageManager()).toString();
                pakName = appinfo.packageName;
                apkInfo.setVersionCode(versionCode);
                apkInfo.setVersionName(versionName);
                apkInfo.setAppName(appName);
                apkInfo.setPackageName(pakName);
                apkInfo.setIcon(icon);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return apkInfo;
    }


    public class APKInfo {
        private String versionName;
        private int versionCode;
        private String appName;
        private String packageName;
        private Drawable icon;

        public String getVersionName() {
            return versionName;
        }

        public void setVersionName(String versionName) {
            this.versionName = versionName;
        }

        public String getAppName() {
            return appName;
        }

        public void setAppName(String appName) {
            this.appName = appName;
        }

        public String getPackageName() {
            return packageName;
        }

        public void setPackageName(String packageName) {
            this.packageName = packageName;
        }

        public Drawable getIcon() {
            return icon;
        }

        public void setIcon(Drawable icon) {
            this.icon = icon;
        }

        public int getVersionCode() {
            return versionCode;
        }

        public void setVersionCode(int versionCode) {
            this.versionCode = versionCode;
        }
    }

    /**
     * 打开已经安装APK，使用默认启动路径
     *
     * @param context
     * @param pak
     */
    public void open(Context context, String pak) {

        try {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(pak);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 第三方程序
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean openThirdApp(Context context, String packageName, String gameID) {
        StatFactory.getInstance().sendGameStart(context,gameID);
        //如果能够普通方式启动则普通启动
        PackageManager pkgMag = context.getPackageManager();
        try {
            Intent intent = pkgMag.getLaunchIntentForPackage(packageName);
            if (intent != null) {
                context.startActivity(intent);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //不行的话用启动自打包方式启动
        // MainActivity完整名
        String mainAct = null;
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setPackage(packageName);
        @SuppressLint("WrongConstant") List<ResolveInfo> list = pkgMag.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(mainAct)) {
            return false;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));
        context.startActivity(intent);
        return true;
    }

    /**
     * 得到手机中所有已安装的应用
     *
     * @param ctx
     * @return
     */
    public List<APKInfo> getAllInstallApkInfo(Context ctx) {

        ArrayList<APKInfo> appList = new ArrayList<APKInfo>();
        try {
            PackageManager packageManager = ctx.getPackageManager();
            List<PackageInfo> packages = packageManager.getInstalledPackages(0);
            for (int i = 0; i < packages.size(); i++) {
                try {

                    PackageInfo packageInfo = packages.get(i);
                    try {
                        if (((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) || ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    APKInfo tmpInfo = new APKInfo();
                    ApplicationInfo applicationInfo = packageInfo.applicationInfo;
//                tmpInfo.setAppName(packageInfo.applicationInfo.loadLabel(packageManager).toString());
                    tmpInfo.setAppName(packageManager.getApplicationLabel(applicationInfo).toString());
                    tmpInfo.setPackageName(packageInfo.packageName);
                    tmpInfo.setVersionName(packageInfo.versionName);
                    tmpInfo.setVersionCode(packageInfo.versionCode);
                    tmpInfo.setIcon(null);
//                tmpInfo.setIcon(packageInfo.applicationInfo.loadIcon(ctx.getPackageManager()));
                    appList.add(tmpInfo);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return appList;
    }

    /* 卸载apk */
    public static void uninstallApk(Context context, String packageName) {
        Uri uri = Uri.parse("package:" + packageName);
        Intent intent = new Intent(Intent.ACTION_DELETE, uri);
        context.startActivity(intent);
    }
}

